<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import { Table, Modal, Form, Input, Button, Space, Tag, message, Radio, DatePicker, Select, Card } from 'ant-design-vue'
import type { TableColumnType } from 'ant-design-vue'
import { taskSubmissionApi } from '@/api/modules/taskSubmission'
import type { TaskSubmissionVO } from '@/types/taskSubmission'
import { SubmissionStatus } from '@/types/taskSubmission'
import { useRoute } from 'vue-router'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
import { SearchOutlined, ReloadOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import FilePreview from '@/components/business/FilePreview.vue'

const route = useRoute()
const taskId = Number(route.params.id)

// 表格数据
const loading = ref(false)
const tableData = ref<TaskSubmissionVO[]>([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '30', '50'],
  // 自定义页码选项的文本
  buildOptionText: (opt: { value: number }) => {
    return `${opt.value} 条/页`
  }
})

// 搜索表单
const searchForm = ref({
  studentName: '',
  studentNo: '',
  status: '',
  timeRange: null as [dayjs.Dayjs, dayjs.Dayjs] | null
})

// 文件预览弹窗
const fileModalVisible = ref(false)
const currentFiles = ref<Array<{ fileName: string; fileUrl: string }>>([])

// 审核弹窗
const reviewModalVisible = ref(false)
const reviewModalLoading = ref(false)
const reviewForm = ref<{ status: SubmissionStatus; reviewComment: string }>({
  status: SubmissionStatus.APPROVED,
  reviewComment: ''
})
const currentSubmissionId = ref<number | null>(null)

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待审核', value: SubmissionStatus.PENDING },
  { label: '已通过', value: SubmissionStatus.APPROVED },
  { label: '已驳回', value: SubmissionStatus.REJECTED }
]

// 表格列配置
const columns: TableColumnType[] = [
  {
    title: '学生姓名',
    dataIndex: 'studentName',
    align: 'center',
    width: 120
  },
  {
    title: '学号',
    dataIndex: 'studentNo',
    align: 'center',
    width: 120
  },
  {
    title: '提交时间',
    dataIndex: 'submitTime',
    align: 'center',
    width: 180,

    customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '提交说明',
    align: 'center',
    dataIndex: 'comment',
    customRender: ({ text }) => text || '-'
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    align: 'center',
    customRender: ({ text }: { text: SubmissionStatus }) => {
      // 兼容处理未知状态
      if (!text) {
        return h(Tag, { color: 'default' }, () => '未知状态');
      }
      
      const config = {
        [SubmissionStatus.PENDING]: { color: 'warning', text: '待审核' },
        [SubmissionStatus.APPROVED]: { color: 'success', text: '已通过' },
        [SubmissionStatus.REJECTED]: { color: 'error', text: '已驳回' },
        [SubmissionStatus.TEACHER_REVIEWING]: { color: 'processing', text: '待审核' }
      };
      
      // 防止未知状态导致错误
      const statusConfig = config[text] || { color: 'default', text: '未知状态' };
      return h(Tag, { color: statusConfig.color }, () => statusConfig.text);
    }
  },
  {
    title: '审核意见',
    dataIndex: 'reviewComment',
    align: 'center',
    customRender: ({ text }) => text || '-'
  },
  {
    title: '审核时间',
    dataIndex: 'reviewTime',
    align: 'center',
    width: 180,
    customRender: ({ text }) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-'
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    customRender: ({ record }) => {
      return h(Space, {}, [
        h(Button, {
          type: 'link',
          onClick: () => handlePreviewFiles(record.files)
        }, () => [
          h(EyeOutlined),
          '查看文件'
        ]),
        h(Button, {
          type: 'link',
          onClick: () => handleReview(record)
        }, () => '审核')
      ])
    }
  }
]

// 获取提交列表
const fetchList = async () => {
  loading.value = true
  try {
    const params: any = {
      taskId,
      page: pagination.value.current - 1,
      size: pagination.value.pageSize
    };
    
    // 添加可选参数
    if (searchForm.value.studentName) {
      params.studentName = searchForm.value.studentName;
    }
    
    if (searchForm.value.studentNo) {
      params.studentNo = searchForm.value.studentNo;
    }
    
    if (searchForm.value.status) {
      params.status = searchForm.value.status as SubmissionStatus;
    }
    
    if (searchForm.value.timeRange?.[0]) {
      params.startTime = searchForm.value.timeRange[0].format('YYYY-MM-DD HH:mm:ss');
    }
    
    if (searchForm.value.timeRange?.[1]) {
      params.endTime = searchForm.value.timeRange[1].format('YYYY-MM-DD HH:mm:ss');
    }
    
    const data = await taskSubmissionApi.getPage(params);
    
    tableData.value = data.content
    pagination.value.total = data.totalElements
  } catch (error) {
    console.error('获取提交列表失败:', error)
    message.error('获取提交列表失败')
  } finally {
    loading.value = false
  }
}

// 处理表格变化
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchList()
}

// 预览文件
const handlePreviewFiles = (files: Array<{ fileName: string; fileUrl: string }>) => {
  currentFiles.value = files
  fileModalVisible.value = true
}

// 下载文件
const handleDownload = (fileUrl: string, fileName: string) => {
  const link = document.createElement('a')
  link.href = fileUrl
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 审核提交
const handleReview = (record: TaskSubmissionVO) => {
  currentSubmissionId.value = record.id
  reviewForm.value.status = SubmissionStatus.APPROVED // 默认状态
  reviewForm.value.reviewComment = '' // 清空评论
  reviewModalVisible.value = true // 显示审核弹窗
}

// 提交审核
const handleSubmitReview = async () => {
  if (!currentSubmissionId.value) return
  reviewModalLoading.value = true
  try {
    await taskSubmissionApi.review(currentSubmissionId.value, reviewForm.value)
    message.success('审核成功')
    reviewModalVisible.value = false
    fetchList() // 刷新列表
  } catch (error) {
    console.error('审核失败:', error)
    message.error('审核失败')
  } finally {
    reviewModalLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    studentName: '',
    studentNo: '',
    status: '',
    timeRange: null
  }
  pagination.value.current = 1
  fetchList()
}

onMounted(() => {
  fetchList()
})
</script>

<template>
  <div class="submission-list-page">
    <Card>
      <template #title>提交列表</template>
      
      <div class="table-toolbar">
        <Space>
          <!-- 学生姓名搜索 -->
          <Input
            v-model:value="searchForm.studentName"
            placeholder="请输入学生姓名"
            style="width: 200px"
            allowClear
          />
          <!-- 学号搜索 -->
          <Input
            v-model:value="searchForm.studentNo"
            placeholder="请输入学号"
            style="width: 200px"
            allowClear
          />
          <!-- 时间范围筛选 -->
          <DatePicker.RangePicker
            v-model:value="searchForm.timeRange"
            :locale="locale"
            :placeholder="['开始时间', '结束时间']"
          />
          <!-- 状态筛选 -->
          <Select
            v-model:value="searchForm.status"
            style="width: 120px"
            :options="statusOptions"
            placeholder="选择状态"
          />
          <!-- 搜索按钮 -->
          <Button type="primary" @click="handleSearch">
            <template #icon><SearchOutlined /></template>
            搜索
          </Button>
          <!-- 重置按钮 -->
          <Button @click="handleReset">
            <template #icon><ReloadOutlined /></template>
            重置
          </Button>
        </Space>
      </div>
      
      <Table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        size="middle"
        :scroll="{ x: 1100 }"
      >
        <template #emptyText>
          <div class="empty-wrapper">
            暂无提交记录
          </div>
        </template>
      </Table>
    </Card>

    <!-- 文件预览弹窗 -->
    <Modal
      v-model:visible="fileModalVisible"
      :maskClosable="false"
      title="文件列表"
      width="800px"
      :footer="null"
    >
      <div class="file-list">
        <div v-for="file in currentFiles" :key="file.fileUrl" class="file-item">
          <FilePreview :file-url="file.fileUrl" />
        </div>
      </div>
    </Modal>

    <!-- 审核弹窗 -->
    <Modal
      v-model:visible="reviewModalVisible"
      title="审核提交"
      :maskClosable="false"
      :confirm-loading="reviewModalLoading"
      @ok="handleSubmitReview"
      @cancel="reviewModalVisible = false"
      ok-text="确定",
      cancel-text="取消"
    >
      <Form
        ref="reviewFormRef"
        :model="reviewForm"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 19 }"
      >
        <Form.Item
          label="审核结果"
          name="status"
          :rules="[{ required: true, message: '请选择审核结果' }]">
          <Radio.Group v-model:value="reviewForm.status">
            <Radio :value="SubmissionStatus.APPROVED">通过</Radio>
            <Radio :value="SubmissionStatus.REJECTED">驳回</Radio>
          </Radio.Group>
        </Form.Item>
        
        <Form.Item label="审核意见" name="reviewComment">
          <Input.TextArea
            v-model:value="reviewForm.reviewComment"
            placeholder="请输入审核意见"
            :rows="4"
            :maxlength="200"
            show-count
          />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<style lang="less" scoped>
.submission-list-page {
  .table-toolbar {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .empty-wrapper {
    padding: 32px 0;
    text-align: center;
    color: rgba(0, 0, 0, 0.25);
  }

  .file-list {
    .file-item {
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }
    }
  }
}
</style>